import React, { useMemo, memo, useState, useEffect, useRef } from "react";
import style from "./index.module.scss";
import { ServiceO, CartO } from "@react-vant/icons";
import { SearchOutline, ReceivePaymentOutline } from "antd-mobile-icons";
import { useNavigate } from "react-router-dom";
import axios from "@/utils/axios";
import { Input } from "antd-mobile";
import hufu from "./images/hufu.png";
import lc from "./images/linchunang.png";
import miaosha from "./images/miaosha.png";
import hot from "./images/rexiaobang.png";
import yimiao from "./images/yimiao.png";
import hufubackground from "./images/hubac.png";
import jk from "./images/jk.png";
import lcback from './images/lcevents.png'
import ms from "./images/ms.png";
import { useAppSelector } from "../../redux/store";
import { PullRefresh, Toast, Loading } from "react-vant";
import { Listface } from "@/Type/git";

const Index = memo(() => {
  const jump = useNavigate();
  const listRef = useRef(null);
  const navigate = useNavigate();
  const [flag, setflag] = useState(true);
  const [page, setPage] = useState(1);
  const [data, setdata] = useState([]);
  const [list, setlist] = useState([]);
  const { cartlist } = useAppSelector((state) => state.cart);

  const topGrid = [
    {
      img: hufu,
      classname: "jk",
      background: hufubackground,
      title: "护肤专场",
    },
    {
      img: hot,
      classname: "hot",
      title: "健康生活",
      background: jk,
    },
  ];
  const bottomGrid = [
    {
      img: miaosha,
      classname: "ms",
      title: "秒杀专场",
      background: ms,
    },
    {
      img: yimiao,
      classname: "yimiao",
    },
    {
      img: lc,
      background:lcback,
      classname: "lc",
    },
  ];

  const getfunlist = () => {
    axios.get("/git").then((res) => {
      setdata(res.data.data);
    });
    axios.get("/serch", { params: { page: 1 } }).then((res) => {
      setlist(res.data.data);
    });
  };

  useEffect(() => {
    const handleScroll = async () => {
      const { scrollTop, clientHeight, scrollHeight } = listRef.current;
      if (scrollTop + clientHeight >= scrollHeight - 10) {
        loadMoreData();
      }
    };
    listRef.current.addEventListener("scroll", handleScroll);
    return () => {
      if (listRef.current != null) {
        listRef.current.removeEventListener("scroll", handleScroll);
      }
    };
  }, [page]);
  const loadMoreData = () => {
    setPage(page + 1);
    setflag(false);
    setTimeout(async () => {
      const response = await axios.get(`/serch?page=${page}`);
      setlist([...list, ...response.data.data]);
      setflag(true);
    }, 1000); // 模拟异步请求
  };
  useEffect(() => {
    getfunlist();
    loadMoreData();
  }, []);

  const onRefresh = (showToast) => {
    return new Promise((resolve) => {
      setPage(1);
      setTimeout(() => {
        if (showToast) {
          Toast.info("刷新成功");
        }
        resolve(true);
      }, 1000);
    });
  };

  return (
    <PullRefresh onRefresh={() => onRefresh(true)} onRefreshEnd={getfunlist}>
      <div className={style.body}>
        {/* 头部搜索模块 */}
        <header className={style.headerbox}>
          <div className={style.header}>
            <div className={style.serchP}>
              <SearchOutline className={style.serch} />
              <Input
                className={style.inp}
                type="text"
                onClick={() => navigate("/shop/shopSerch:item")}
              />
              <button>搜索</button>
              <ServiceO
                className={style.service}
                onClick={() => {
                  jump("/CustomerService");
                }}
              />
            </div>
            <div className={style.gitbox}>
              {data.map((item: { img: string; title: string }, index) => (
                <div
                  key={index}
                  onClick={() => {
                    navigate("/shop/shopSerch:item", { state: item });
                  }}
                >
                  <img src={item.img} alt={item.title} />
                  <p>{item.title}</p>
                </div>
              ))}
            </div>
          </div>
        </header>
        {/* 问诊模块 */}
        <div className={style.interrogation}>
          <h3>
            <ReceivePaymentOutline />
            问诊开药
          </h3>
          <p>
            适用于常见病、病情稳定的慢性病复诊患者
            <button
              onClick={() => {
                jump("/fast");
              }}
            >
              立即问诊
            </button>
          </p>
        </div>
        {/* 中心推荐区 */}
        <div className={style.main}>
          <div className={style.top}>
            {topGrid.map((item, index) => {
              return (
                <div
                  key={index}
                  onClick={() => {
                    jump("/ShopEventsDetail:item", { state: { item } });
                    console.log(item, "item");
                  }}
                >
                  <img src={item.img} alt="" />
                </div>
              );
            })}
          </div>
          <div className={style.bottom}>
            {bottomGrid.map((item, index) => {
              return (
                <div
                  key={index}
                  onClick={() => {
                    jump("/ShopEventsDetail:item", { state: { item } });
                  }}
                >
                  <img src={item.img} alt="" />
                </div>
              );
            })}
          </div>
        </div>
        {/* 列表区 */}
        <div
          ref={listRef}
          style={{ height: `${page * 50}vh`, overflowY: "scroll" }}
          className={style.list}
        >
          {list.map((item: Listface, index) => {
            return (
              <div
                key={index}
                onClick={() => {
                  jump("/jkshop/detail:item", { state: { item } });
                }}
              >
                <img src={item.img} alt="" />
                <p>
                  {item?.otc && <span className={style.otc}>{item?.otc}</span>}
                  &emsp;
                  {item.desc}
                </p>
                <p>{item.type}</p>
                <p className={style.price}>￥{item.price}</p>
              </div>
            );
          })}
        </div>
        <Loading
          className={style.rvloading}
          vertical={true}
          style={{ display: flag }}
        >
          加载中......
        </Loading>
        <div
          className={style.cartbox}
          onClick={() => {
            navigate("/cart");
          }}
        >
          {cartlist?.length !== 0 && (
            <p className={style.cartnum}>{cartlist?.length} </p>
          )}

          <CartO className={style.carticon} />
        </div>
      </div>
    </PullRefresh>
  );
});

export default Index;
